package com.qkst.website.web.controller;


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.qkst.website.backstage.bean.CatalogBean;
import com.qkst.website.backstage.bean.ProductBean;
import com.qkst.website.common.core.BaseController;
import com.qkst.website.common.core.Pager;
import com.qkst.website.common.utils.HttpRequest;
import com.qkst.website.common.utils.SetEnums;
import com.qkst.website.web.bean.UserBean;
import com.qkst.website.web.bean.UserDetailBean;
import com.qkst.website.web.service.CatalogService;
import com.qkst.website.web.service.ProductService;
import com.qkst.website.web.service.UserService;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.javabeans.weibo.Company;
import com.qq.connect.oauth.Oauth;
import com.qq.connect.utils.json.JSONException;
import com.qq.connect.utils.json.JSONObject;

@Controller
@RequestMapping("/web")
public class WebLoginController extends BaseController{
	
	private static final Logger log = LoggerFactory.getLogger(WebLoginController.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private CatalogService catalogService;
	
	@Autowired
	private ProductService productService;

	/**
	 * QQ联合登陆 进入授权页面前
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/login.do", method = { RequestMethod.GET })
	public void login(HttpServletRequest request,HttpServletResponse response) throws IOException{
	   response.setContentType("text/html;charset=utf-8");
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
        } catch (QQConnectException e) {
            e.printStackTrace();
        }
	}
	
	/**
	 * QQ联合登陆回调
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ParseException 
	 * @throws JSONException 
	 */
	@RequestMapping(value = "/qq_callBack.do", method = { RequestMethod.GET })
	public void qq_callBack(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException, JSONException{
		
	    response.setContentType("text/html; charset=utf-8");
	    
	    ModelAndView mv=this.webModelAndView("index");
	    
	    UserBean loginUser= new UserBean();//创建登陆用户
	    
        UserDetailBean userDetail =  new UserDetailBean();//创建登陆用户明细
        
      //  PrintWriter out = response.getWriter();

        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);

            String accessToken   = null,
                   openID        = null;
            long tokenExpireIn = 0L;

            if (accessTokenObj.getAccessToken().equals("")) {
//                我们的网站被CSRF攻击了或者用户取消了授权
//                做一些数据统计工作
                log.error("没有获取到响应参数");
            } else {
                accessToken = accessTokenObj.getAccessToken();
                tokenExpireIn = accessTokenObj.getExpireIn();

                request.getSession().setAttribute("access_token", accessToken);
                request.getSession().setAttribute("token_expirein", String.valueOf(tokenExpireIn));

                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj =  new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                log.info("欢迎你，代号为 " + openID + " 的用户!");
               // out.println("欢迎你，代号为 " + openID + " 的用户!");
                request.getSession().setAttribute("OPENID", openID);
                loginUser.setQqOpenId(openID);
                loginUser=userService.findUserByCondition(loginUser);
                
                if(loginUser==null || loginUser.getUserId()==null){ //用户未注册过,需要授权登陆并注册用户信息
                	loginUser = new UserBean();
                	 //request.getSession().setAttribute("demo_openid", openID);
                    //out.println("<a href=" + "/shuoshuoDemo.html" +  " target=\"_blank\">去看看发表说说的demo吧</a>");
                     // 利用获取到的accessToken 去获取当前用户的openid --------- end
                     
                     //out.println("<p> start -----------------------------------利用获取到的accessToken,openid 去获取用户在Qzone的昵称等信息 ---------------------------- start </p>");
                     UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                     UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                    // out.println("<br/>");
                     if (userInfoBean.getRet() == 0) {
                    	loginUser.setQqOpenId(openID);
                     	loginUser.setNickName(userInfoBean.getNickname());
                     	loginUser.setUserName(openID);
                     	loginUser.setPassword(accessToken);
                     	userDetail.setSex(userInfoBean.getGender());
                     } else {
                     	log.error("很抱歉，我们没能正确获取到您的信息，原因是： " + userInfoBean.getMsg());
                     }
                     
                     String param="access_token="+accessToken+"&oauth_consumer_key=101405850&openid="+openID;
                     String result=HttpRequest.sendGet("https://graph.qq.com/user/get_user_info",param);
                     JSONObject json =new JSONObject(result);
                     if("0".equals(json.get("ret").toString())){
                    	 System.out.println(">>>>>>>>>>>>>>>>>>>>>"+json.get("figureurl_qq_1"));
                         userDetail.setFigureurl(json.get("figureurl").toString());
                         userDetail.setFigureurl1(json.get("figureurl_1").toString());
                         userDetail.setFigureurl2(json.get("figureurl_2").toString());
                         userDetail.setFigureurlQQ1(json.get("figureurl_qq_1").toString());
                         userDetail.setFigureurlQQ2(json.get("figureurl_qq_2").toString());
                     }
                     
                     com.qq.connect.api.weibo.UserInfo weiboUserInfo = new com.qq.connect.api.weibo.UserInfo(accessToken, openID);
                     com.qq.connect.javabeans.weibo.UserInfoBean weiboUserInfoBean = weiboUserInfo.getUserInfo();
                     if (weiboUserInfoBean.getRet() == 0) {
                     	if(weiboUserInfoBean.getBirthday().getYear()>0){
                     		String birthday=weiboUserInfoBean.getBirthday().getYear()+"-"+weiboUserInfoBean.getBirthday().getMonth()+"-"+weiboUserInfoBean.getBirthday().getDay();
                         	SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                         	userDetail.setBirthday(fmt.parse(birthday));
                     	}
                         StringBuffer sb = new StringBuffer();
                         sb.append("<p>所在地:" + weiboUserInfoBean.getCountryCode() + "-" + weiboUserInfoBean.getProvinceCode() + "-" + weiboUserInfoBean.getCityCode()
                                  + weiboUserInfoBean.getLocation());

                         //获取用户的公司信息---------------------------start
                         ArrayList<Company> companies = weiboUserInfoBean.getCompanies();
                         if (companies.size() > 0) {
                             //有公司信息
                             for (int i=0, j=companies.size(); i<j; i++) {
                                 sb.append("<p>曾服役过的公司：公司ID-" + companies.get(i).getID() + " 名称-" +
                                 companies.get(i).getCompanyName() + " 部门名称-" + companies.get(i).getDepartmentName() + " 开始工作年-" +
                                 companies.get(i).getBeginYear() + " 结束工作年-" + companies.get(i).getEndYear());
                             }
                         } else {
                             //没有公司信息
                         }
                         //获取用户的公司信息---------------------------end
                         log.info(sb.toString());
                         //out.println(sb.toString());

                     } else {
                         //out.println("很抱歉，我们没能正确获取到您的信息，原因是： " + weiboUserInfoBean.getMsg());
                     	log.warn("很抱歉，我们没能正确获取到您的信息，原因是： " + weiboUserInfoBean.getMsg());
                     }

                    // out.println("<p> end -----------------------------------利用获取到的accessToken,openid 去获取用户在微博的昵称等信息 ---------------------------- end </p>");
                     loginUser.setUserDetail(userDetail);
                     userService.save(loginUser, mv);
                }else{
                	String param="access_token="+accessToken+"&oauth_consumer_key=101405850&openid="+openID;
                    String result=HttpRequest.sendGet("https://graph.qq.com/user/get_user_info",param);
                    JSONObject json =new JSONObject(result);
                    System.out.println(">>>>>>>>>>>>>>>>>>>>>"+json.toString());
                    if("0".equals(json.get("ret").toString())){
                        userDetail.setFigureurl(json.get("figureurl").toString());
                        userDetail.setFigureurl1(json.get("figureurl_1").toString());
                        userDetail.setFigureurl2(json.get("figureurl_2").toString());
                        userDetail.setFigureurlQQ1(json.get("figureurl_qq_1").toString());
                        userDetail.setFigureurlQQ2(json.get("figureurl_qq_2").toString());
                        userDetail.setSex(json.get("gender").toString());
                        loginUser.setNickName(json.get("nickname").toString());
                        loginUser.setUserDetail(userDetail);
                        loginUser.setLastLoinTime(new Date());
                        loginUser.setLastUpdate(new Date());
                        userService.updateUser(loginUser);//更新用户信息
                    }
                }
               
            }
        } catch (QQConnectException e) {
        	log.error("QQ联合登陆异常!");
        	e.printStackTrace();
        }
        request.getSession().setAttribute(SetEnums._LOGIN_USER.toString(),loginUser);
        response.sendRedirect(request.getContextPath()+"/web/index.html");
	}
	
	/**
	 * 进入登陆首页
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/index.html", method = {RequestMethod.GET})
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response) throws IOException{
		ModelAndView mv = this.webModelAndView("index");
		List<CatalogBean> catalogList=catalogService.list(new CatalogBean());//获取分类
		List<ProductBean> productList = new ArrayList<ProductBean>();
		Pager pager = new Pager();
		for(CatalogBean catalog :catalogList){
			if("VIEDO".equals(catalog.getCode())){//视频
				if(catalog.getCatgroupList()!=null && !catalog.getCatgroupList().isEmpty()){
					ProductBean product = new ProductBean();
					product.setPage(1);
					product.setRows(10);
					product.setCatgroup(catalog.getCatgroupList().get(0));
					//分页查询产品列表
					productList=productService.queryProductList(product);
					//产品总记录数
					int records=productService.queryCount(product);
					pager.setRecords(records);
				}
				break;
			}
		}
		mv.addObject("productList", productList);//返回产品列表
		mv.addObject("pager", pager);//返回总记录数据
		mv.addObject("catalogList",catalogList);
		return mv;
	}
	
	/**
	 * 退出登录
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/logout.do", method = { RequestMethod.GET })
	public void loginout(HttpServletRequest request,HttpServletResponse response) throws IOException{
		request.getSession().setAttribute(SetEnums._LOGIN_USER.toString(),null);//置空登陆session
		response.sendRedirect(request.getContextPath());//重回首页
	}
	

}
